package com.my.ph.service.impl;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.my.ph.service.FileDirectoryService;
import com.my.ph.entity.file.FileInfo;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
@Slf4j
public class FileDirectoryServiceImpl implements FileDirectoryService {

    private List<FileInfo> getFileInfo(List<FileInfo> list, String path, int deep) {
        log.info("文件路径：{}， 深度：{}", path, deep);
        if (list == null) list = ListUtil.empty();
        File[] files;
        if (path == null) {
            files = File.listRoots();
            if (files == null || files.length == 0) throw new RuntimeException("无法读取系统文件夹");
        } else {
            File file = new File(path);
            if (!file.exists()) return null;
            if (file.isFile()) return null;
            files = file.listFiles();
            if (files == null || files.length == 0) return list;
        }
        list = Arrays.stream(files).map(f -> new FileInfo(StrUtil.blankToDefault(f.getName(), f.getPath().replace("\\", "")), f.getPath(), f.isFile() ? "file" : "folder", f.isFile() ? f.length() : 0L, f.isFile() ? FileUtil.getSuffix(f) : null, f.isFile() ? null : ListUtil.empty(), null)).toList();
        if (deep > 0 && !list.isEmpty()) list.forEach(fileInfo -> fileInfo.setChildren(getFileInfo(fileInfo.getChildren(), fileInfo.getFilePath(), deep - 1)));
        return list;
    }

    @Override
    public List<FileInfo> getRoot() {
        return getFileInfo(null, null, 1);
    }

    @Override
    public List<FileInfo> getChildren(String path) {
        return getFileInfo(null, path, 1);
    }

    @Override
    public void getTorrent(String filePath, HttpServletResponse response) throws IOException {
        File uploadFile = new File(URLUtil.decode(filePath));
        ServletOutputStream os = response.getOutputStream();
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setContentLength((int) uploadFile.length());
        response.addHeader("Content-Disposition","attachment;filename=" + URLUtil.encode(uploadFile.getName()));
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }

}
